<template>
  <view class="user-container">
    <!-- 星空背景顶部区域 -->
    <view class="user-header">
      <view class="user-info-wrapper">
        <view class="avatar-container">
          <image class="avatar" :src="formatAvatar(userInfo.avatar) || '/static/logo.png'" mode="aspectFill"></image>
          <image class="vip-badge" v-if="userInfo.isVip" src="/common/images/vip.png" mode="aspectFit"></image>
        </view>
        <view class="user-details">
          <text class="username">{{ userInfo.username || '未登录' }}</text>
          <text class="user-id" v-if="userInfo.phone">{{ formatPhone(userInfo.phone) }}</text>
        </view>
        <image class="message-icon" src="/common/images/message.png" mode="aspectFit"></image>
      </view>
      

    </view>
    
    <!-- 数据统计卡片 -->
    <view class="stats-card">
      <view class="stat-item">
        <text class="stat-number">{{ userInfo.collections || 0 }}</text>
        <text class="stat-label">收藏</text>
      </view>
      <view class="stat-item" @click="navigateToOrderList()">
        <text class="stat-number">{{ userInfo.orders || 0 }}</text>
        <text class="stat-label">订单</text>
      </view>
      <view class="stat-item">
        <text class="stat-number">{{ userInfo.articles || 0 }}</text>
        <text class="stat-label">文章</text>
      </view>
      <view class="stat-item">
        <text class="stat-number">{{ userInfo.views || 0 }}</text>
        <text class="stat-label">浏览</text>
      </view>
    </view>
    
    <!-- 我的订单 -->
    <view class="orders-section">
      <view class="section-header">
        <text class="section-title">我的订单</text>
        <view class="section-more">
          <text @click="navigateToOrderList()">全部订单</text>
          <image class="arrow-icon" src="/common/images/arrow-right.png" mode="aspectFit"></image>
        </view>
      </view>
      
      <view class="order-status">
        <view class="status-item" @click="navigateToOrderList('pending')">
          <image class="status-icon" src="/common/images/payment.png" mode="aspectFit"></image>
          <text class="status-label">待付款</text>
          <view class="badge" v-if="userInfo.waitingPayment > 0">{{ userInfo.waitingPayment }}</view>
        </view>
        <view class="status-item" @click="navigateToOrderList('paid')">
          <image class="status-icon" src="/common/images/use.png" mode="aspectFit"></image>
          <text class="status-label">待使用</text>
          <view class="badge" v-if="userInfo.waitingUse > 0">{{ userInfo.waitingUse }}</view>
        </view>
        <view class="status-item" @click="navigateToOrderList('comment')">
          <image class="status-icon" src="/common/images/comment.png" mode="aspectFit"></image>
          <text class="status-label">待评价</text>
          <view class="badge" v-if="userInfo.waitingComment > 0">{{ userInfo.waitingComment }}</view>
        </view>
        <view class="status-item" @click="navigateToOrderList('canceled')">
          <image class="status-icon" src="/common/images/refund.png" mode="aspectFit"></image>
          <text class="status-label">退款售后</text>
          <view class="badge" v-if="userInfo.refund > 0">{{ userInfo.refund }}</view>
        </view>
      </view>
    </view>
    
    <!-- 功能菜单 -->
    <view class="menu-section">
      <view class="menu-item" @click="showUnderDevelopment">
        <image class="menu-icon" src="/common/images/invite.png" mode="aspectFit"></image>
        <text class="menu-label">邀请好友</text>
        <image class="arrow-icon" src="/common/images/arrow-right.png" mode="aspectFit"></image>
      </view>
      <view class="menu-item" @click="showUnderDevelopment">
        <image class="menu-icon" src="/common/images/contacts.png" mode="aspectFit"></image>
        <text class="menu-label">常用联系人</text>
        <image class="arrow-icon" src="/common/images/arrow-right.png" mode="aspectFit"></image>
      </view>
      <view class="menu-item" @click="showUnderDevelopment">
        <image class="menu-icon" src="/common/images/invoice.png" mode="aspectFit"></image>
        <text class="menu-label">发票</text>
        <image class="arrow-icon" src="/common/images/arrow-right.png" mode="aspectFit"></image>
      </view>
      <view class="menu-item" @click="navigateTo('settings')">
        <image class="menu-icon" src="/common/images/settings.png" mode="aspectFit"></image>
        <text class="menu-label">设置</text>
        <image class="arrow-icon" src="/common/images/arrow-right.png" mode="aspectFit"></image>
      </view>
    </view>
    
    <!-- 退出登录按钮 -->
    <button class="logout-button" @click="handleLogout" v-if="userInfo.username">退出登录</button>
    
    <view v-if="loading" class="loading">
      <text>加载中...</text>
    </view>
    
    <view v-if="error" class="error">
      <text>{{ error }}</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {onShow} from '@dcloudio/uni-app'
import { userApi } from '@/common/api'
import { orderApi } from '@/common/api/order.js'
import { articleApi } from '@/common/api/article.js'

// 用户信息响应式数据
const userInfo = ref({
  // 默认数据，实际会被API返回的数据覆盖
  collections: 234,
  orders: 234,
  articles: 0,
  views: 234,
  waitingPayment: 0,
  waitingUse: 0,
  waitingComment: 0,
  refund: 0
})
const loading = ref(false)
const error = ref('')

// 格式化头像URL，去除多余的反引号和空格
const formatAvatar = (avatar) => {
  if (!avatar) return ''
  // 去除前后的反引号和空格
  return avatar.replace(/[`\s]/g, '')
}

// 获取用户信息的函数
const fetchUserInfo = async () => {
  try {
    loading.value = true
    error.value = ''
    const res = await userApi.getUserInfo()
    // 根据API返回的数据结构，正确赋值
    if (res.data) {
      userInfo.value = {
        ...userInfo.value, // 保留默认值
        ...res.data // 覆盖API返回的数据
      }
    }
  } catch (err) {
    console.error('获取用户信息失败:', err)
    error.value = err.message || '获取用户信息失败'
  } finally {
    loading.value = false
  }
}

// 获取用户订单数和状态分布
const fetchUserOrderCount = async () => {
  try {
    // 从本地存储获取用户ID
    const storedUserInfo = uni.getStorageSync('userInfo')
    if (!storedUserInfo) {
      console.log('未登录，跳过获取订单数')
      return
    }
    
    // 尝试获取用户ID，考虑不同的字段名
    const userId = storedUserInfo.userId || storedUserInfo.id || storedUserInfo.user_id
    if (!userId) {
      console.log('用户信息中未找到ID字段')
      return
    }
    
    const res = await orderApi.getUserOrderCount(userId)
    if (res.status === 'success' && res.data) {
      // 更新订单总数
      console.log('订单总数:', res.data.total)
      userInfo.value.orders = res.data.total || 0
      
      // 更新各状态订单数
      if (res.data.statusCount) {
        // 映射状态码到对应的属性名
        const statusMap = {
          'pending': 'waitingPayment',
          'paid': 'waitingUse',
          'comment': 'waitingComment',
          'refunded': 'refund'
        }
        
        Object.entries(res.data.statusCount).forEach(([status, count]) => {
          if (statusMap[status]) {
            userInfo.value[statusMap[status]] = count
          }
        })
      }
    }
  } catch (err) {
    console.error('获取用户订单数失败:', err)
    // 不显示错误，使用默认值
  }
}

// 获取用户发布的文章数
const fetchUserArticleCount = async () => {
  try {
    // 从本地存储获取用户ID
    const storedUserInfo = uni.getStorageSync('userInfo')
    if (!storedUserInfo) {
      console.log('未登录，跳过获取文章数')
      return
    }
    
    // 尝试获取用户ID，考虑不同的字段名
    const userId = storedUserInfo.userId || storedUserInfo.id || storedUserInfo.user_id
    if (!userId) {
      console.log('用户信息中未找到ID字段')
      return
    }
    
    const res = await articleApi.getUserArticleCount(userId)
    if (res.status === 'success' && res.data) {
      userInfo.value.articles = res.data.total || 0
    }
  } catch (err) {
    console.error('获取用户文章数失败:', err)
    // 不显示错误，使用默认值
  }
}

// 获取用户收藏的文章数
const fetchUserFavoriteCount = async () => {
  try {
    // 从本地存储获取用户ID
    const storedUserInfo = uni.getStorageSync('userInfo')
    if (!storedUserInfo) {
      console.log('未登录，跳过获取收藏数')
      return
    }
    
    // 尝试获取用户ID，考虑不同的字段名
    const userId = storedUserInfo.userId || storedUserInfo.id || storedUserInfo.user_id
    if (!userId) {
      console.log('用户信息中未找到ID字段')
      return
    }
    
    const res = await articleApi.getUserFavoriteCount(userId)
    if (res.status === 'success' && res.data) {
      userInfo.value.collections = res.data.total || 0
    }
  } catch (err) {
    console.error('获取用户收藏数失败:', err)
    // 不显示错误，使用默认值
  }
}
//电话格式
const formatPhone = (phone) => {
  if (!phone) return ''
  // 去除前后的空格
  phone = phone.trim()
  // 匹配手机号格式，保留前三位和后四位
  return phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
}

// 显示待开发中提示
const showUnderDevelopment = () => {
  uni.showToast({
    title: '待开发中',
    icon: 'none',
    duration: 2000
  })
}

// 退出登录处理函数
const handleLogout = () => {
  // 弹出确认对话框
  uni.showModal({
    title: '退出登录',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        // 清除本地存储的用户信息和token
        uni.removeStorageSync('token')
        uni.removeStorageSync('userInfo')
        
        // 显示退出成功提示
        uni.showToast({
          title: '退出成功',
          icon: 'success',
          duration: 1500
        })
        
        // 重置用户信息
        userInfo.value = {
          collections: 234,
          orders: 234,
          coupons: 12,
          views: 234,
          waitingPayment: 1,
          waitingUse: 2,
          waitingComment: 0,
          refund: 0
        }
        
        // 延迟跳转到登录页面
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/login/login'
          })
        }, 1500)
      }
    }
  })
}

// 导航到其他页面
const navigateTo = (page) => {
  let url = ''
  switch (page) {
    case 'invite':
      url = '/pages/user/invite'
      break
    case 'contacts':
      url = '/pages/user/contacts'
      break
    case 'invoice':
      url = '/pages/user/invoice'
      break
    case 'settings':
      url = '/pages/user/profile-edit'  // 跳转到个人信息编辑页面
      break
    default:
      url = '/pages/user/user'
  }
  
  uni.navigateTo({
    url
  })
}

// 导航到订单列表页面（按状态筛选）
const navigateToOrderList = (status) => {
  // 从本地存储获取用户ID
  const storedUserInfo = uni.getStorageSync('userInfo')
  const userId = storedUserInfo ? (storedUserInfo.userId || storedUserInfo.id || storedUserInfo.user_id) : ''
  
  // 构建导航参数
  const queryParams = []
  if (userId) {
    queryParams.push(`userId=${userId}`)
  }
  if (status) {
    queryParams.push(`status=${status}`)
  }
  
  // 导航到订单列表页面
  uni.navigateTo({
    url: `/pages/orders/list-status?${queryParams.join('&')}`
  })
}

// 数据刷新函数，集中管理所有数据获取操作
const refreshData = () => {
  fetchUserInfo()
  fetchUserOrderCount()
  fetchUserArticleCount()
  fetchUserFavoriteCount()
}

// 组件挂载时获取用户信息
onMounted(() => {
  refreshData()
})

// 页面显示时重新获取数据（解决从其他页面返回时数据不更新的问题）
onShow(() => {
  refreshData()
})
</script>

<style lang="scss" scoped>
.user-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  position: relative;
  
  // 星空背景
  .user-header {
    background: linear-gradient(135deg, #1a1a4e 0%, #2a3f7e 100%);
    padding-top: 80rpx;
    padding-bottom: 40rpx;
    padding-left: 30rpx;
    padding-right: 30rpx;
    position: relative;
    
    // 星空效果
    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-image: 
        radial-gradient(white, rgba(255,255,255,.2) 2px, transparent 4px),
        radial-gradient(white, rgba(255,255,255,.15) 1px, transparent 2px),
        radial-gradient(white, rgba(255,255,255,.1) 2px, transparent 3px);
      background-size: 550px 550px, 350px 350px, 250px 250px;
      background-position: 0 0, 40px 60px, 130px 270px;
      opacity: 0.6;
    }
    
    .user-info-wrapper {
      display: flex;
      align-items: center;
      margin-bottom: 40rpx;
      position: relative;
      
      .avatar-container {
        width: 160rpx;
        height: 160rpx;
        border-radius: 50%;
        overflow: hidden;
        border: 4rpx solid rgba(255, 255, 255, 0.3);
        position: relative;
        
        .avatar {
          width: 100%;
          height: 100%;
        }
        
        .vip-badge {
          position: absolute;
          bottom: 0;
          right: 0;
          width: 48rpx;
          height: 48rpx;
        }
      }
      
      .user-details {
        margin-left: 30rpx;
        flex: 1;
        
        .username {
          color: #fff;
          font-size: 40rpx;
          font-weight: bold;
          display: block;
          margin-bottom: 10rpx;
        }
        
        .user-id {
          color: rgba(255, 255, 255, 0.8);
          font-size: 28rpx;
        }
      }
      
      .message-icon {
        width: 60rpx;
        height: 60rpx;
      }
    }
    

  }
  
  // 数据统计卡片
  .stats-card {
    background-color: #fff;
    margin: -30rpx 30rpx 30rpx 30rpx;
    border-radius: 20rpx;
    padding: 40rpx 20rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
    display: flex;
    justify-content: space-around;
    position: relative;
    
    .stat-item {
      text-align: center;
      
      .stat-number {
        font-size: 40rpx;
        font-weight: bold;
        color: #333;
        display: block;
        margin-bottom: 10rpx;
      }
      
      .stat-label {
        font-size: 28rpx;
        color: #999;
      }
    }
  }
  
  // 订单部分
  .orders-section {
    background-color: #fff;
    margin: 0 30rpx 20rpx 30rpx;
    border-radius: 20rpx;
    padding: 30rpx;
    
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30rpx;
      
      .section-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .section-more {
        display: flex;
        align-items: center;
        
        text {
          font-size: 28rpx;
          color: #999;
          margin-right: 10rpx;
        }
        
        .arrow-icon {
          width: 24rpx;
          height: 24rpx;
        }
      }
    }
    
    .order-status {
      display: flex;
      justify-content: space-around;
      
      .status-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        position: relative;
        
        .status-icon {
          width: 80rpx;
          height: 80rpx;
          margin-bottom: 15rpx;
        }
        
        .status-label {
          font-size: 28rpx;
          color: #666;
        }
        
        .badge {
          position: absolute;
          top: 0;
          right: 10rpx;
          background-color: #ff4d4f;
          color: #fff;
          font-size: 20rpx;
          padding: 4rpx 12rpx;
          border-radius: 16rpx;
          min-width: 32rpx;
          text-align: center;
        }
      }
    }
  }
  
  // 功能菜单
  .menu-section {
    background-color: #fff;
    margin: 0 30rpx 30rpx 30rpx;
    border-radius: 20rpx;
    overflow: hidden;
    
    .menu-item {
      display: flex;
      align-items: center;
      padding: 35rpx 30rpx;
      border-bottom: 1rpx solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .menu-icon {
        width: 48rpx;
        height: 48rpx;
        margin-right: 30rpx;
      }
      
      .menu-label {
        font-size: 32rpx;
        color: #333;
        flex: 1;
      }
      
      .arrow-icon {
        width: 24rpx;
        height: 24rpx;
      }
    }
  }
  
  // 退出登录按钮
  .logout-button {
    width: calc(100% - 60rpx);
    margin: 0 30rpx 60rpx 30rpx;
    background-color: #fff;
    color: #e0e0e0;
    border: 1rpx solid #c3c2c2;
    font-size: 32rpx;
    padding: 25rpx 0;
    border-radius: 10rpx;
  }
  
  // 加载和错误提示
  .loading, .error {
    margin-top: 30rpx;
    text-align: center;
    font-size: 28rpx;
    padding: 20rpx;
  }
  
  .error {
    color: #ff6b6b;
    background-color: #ffe5e5;
    border-radius: 8rpx;
  }
}
</style>
